package org.happen.android.thrid.other;

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.happen.android.core.net.AppHttpClient;
import org.liushui.mycommons.android.log.McLog;

import android.text.TextUtils;

import com.google.gson.Gson;

/**
 * 号码归属地查询
 */
public class QueryTelphoneCity
{

	/**
	 * http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?qq-pf-to=pcqq.
	 * discussion&tel=13816946250
	 * 
	 * <pre>
	 * __GetZoneResult_ = {
	 *     mts:'1381694',
	 *     province:'上海',
	 *     catName:'中国移动',
	 *     telString:'13816946250',
	 *     areaVid:'29423',
	 *     ispVid:'3236139'
	 * }
	 * </pre>
	 */
	static final String QUERY_URL = "http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?qq-pf-to=pcqq.discussion&tel=";

	/**
	 * <pre>
	 * json转化而来
	 * {
	 *     mts:'1381694',
	 *     province:'上海',
	 *     catName:'中国移动',
	 *     telString:'13816946250',
	 *     areaVid:'29423',
	 *     ispVid:'3236139'
	 * }
	 * </pre>
	 */
	public static class QueryResult
	{
		public String mts;
		public String province;
		public String catName;
		public String telString;
		public String areaVid;
		public String ispVid;

		public boolean validate()
		{
			if (TextUtils.isEmpty(province) || TextUtils.isEmpty(catName))
			{
				return false;
			}
			return true;
		}

		public String toString()
		{
			return "QueryResult [mts=" + mts + ", province=" + province + ", catName=" + catName + ", telString=" + telString + ", areaVid=" + areaVid + ", ispVid=" + ispVid + "]";
		}
	}

	/**
	 * 查询号码归属地，建议在线程中使用
	 * 
	 * @param num
	 * @return
	 */
	public static QueryResult query(String num)
	{
		HttpClient httpclient = AppHttpClient.getInstance().createClient();
		HttpGet httpGet = new HttpGet(QUERY_URL + num);
		HttpResponse httpResponse;
		try
		{
			httpResponse = httpclient.execute(httpGet);
			int code = httpResponse.getStatusLine().getStatusCode();
			McLog.i("http response status code:" + code);
			if (code == HttpStatus.SC_OK)
			{
				String res = EntityUtils.toString(httpResponse.getEntity(), HTTP.UTF_8);
				McLog.i(res);
				StringBuilder sb = new StringBuilder(res);
				Gson gson = new Gson();
				sb.delete(0, sb.indexOf("{"));
				McLog.i(sb);
				QueryResult result = gson.fromJson(sb.toString(), QueryResult.class);
				return result;
			}
		} catch (ClientProtocolException e)
		{
			e.printStackTrace();
		} catch (IOException e)
		{
			e.printStackTrace();
		}
		return null;
	}
}